<?php
// +----------------------------------------------------------------------
// | zhanshop-admin / HttpException.php    [ 2023/9/1 17:22 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2011~2023 zhangqiquan All rights reserved.
// +----------------------------------------------------------------------
// | Author: zhangqiquan <768617998@qq.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\exception;

use app\library\BaseController;
use Swoole\Http\Request;
use zhanshop\App;
use zhanshop\Error;
use zhanshop\Log;

class HttpException extends Error
{
    protected $debug = true;
    public function __construct()
    {
        $this->debug = App::config()->get("app.app_debug");
    }

    /**
     * 错误处理
     * @param Request $request
     * @param \Throwable $error
     * @return array
     */
    public function handle($request, $error){
        $data = null;
        $result = App::make(BaseController::class)->result($data, $error->getMessage(), $error->getCode());
        $this->errlog($request, $error);
        return $result;
    }
    /**
     * 错误处理
     * @param \zhanshop\Request $request
     * @param \Throwable $error
     * @return array
     */
    private function errlog($request, $error)
    {
        if($error->getCode() === 404 && $this->debug === false) return false;
        App::log()->push(json_encode([
            'time' => date('Y-m-d H:i:s', $request->time()),
            'url' => $request->server('request_uri'),
            'ip' => $request->realIp(),
            'agent' => $request->header('user-agent'),
            'code' => $error->getCode(),
            'msg' => $error->getMessage(),
            'request' => [
                'get' => $request->get(),
                'post' => $request->post(),
                'file' => $request->files(),
                'raw' => mb_substr(strval($request->rawRequest()->getContent()), 0, 4096),
            ],
            'response' => $error->getFile().'('.$error->getLine().'): '.$error->getMessage().PHP_EOL.$error->getTraceAsString(),
            'runtime' => microtime(true) - $request->time(true),
        ], JSON_UNESCAPED_SLASHES + JSON_UNESCAPED_UNICODE), Log::ERROR, "ERROR");
    }
}